//
//  FlipViewControllers.m
//  ViewControllersContainer
//
//  Created by 李劲成 on 16/4/13.
//  Copyright © 2016年 ljc. All rights reserved.
//

#import "FlipViewControllers.h"

@interface FlipViewControllers ()

@property (nonatomic, retain) UIButton *infoButton;

@property (nonatomic, retain) UINavigationBar *navBar;

@property (nonatomic, retain) NSArray *controllers;

// 用于观察的变量
@property (nonatomic, assign) BOOL reservedOrder;


@end

@implementation FlipViewControllers

- (void)dealloc {
    [_infoButton release];
    [_navBar release];
    [_controllers release];
    [super dealloc];
}
#pragma mark - 自定义初始化.
- (instancetype)initWithFrontController:(UIViewController *)front andBackController:(UIViewController *)back {
    self = [super init];
    if (self) {
//        if (!front) {
//            NSLog(@"ErrorReason:Attempting to create FlipViewController without a root controller.");
//            return self;
//        }
//        if (back) {
            self.controllers = @[front, back];
//        }
//        else {
//            self.controllers = @[front];
//        }
        

        self.reservedOrder = NO;
    }
    return self;
}
- (void)loadView {
    self.view = [[UIView alloc] init];
    self.view.backgroundColor = [UIColor blackColor];
}
#pragma mark - 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];

    // Do any additional setup after loading the view.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // 判断数组个数是否为空
//    if (!self.controllers.count)
//    {
//        NSLog(@"Error: No root view controller");
//        return;
//    }
//    
    UIViewController *front = [self.controllers[0] retain];
    UIViewController *back = nil;
    // 判断数组个数是否大于1
    if (self.controllers.count > 1) {
        back = [[self.controllers[1] retain]autorelease];
    }
    // 添加子控制器
    [self addChildViewController:front];
    // 添加子视图
    [self.view addSubview:front.view];
    // 移除父控制器后调用
#warning ?
    [front didMoveToParentViewController:self];
    // 检查是否模态推出.
    BOOL isPresented = self.isBeingPresented;
    // 清除
    if (self.navBar || self.infoButton) {
        // 从父视图中移除
        [self.navBar removeFromSuperview];
        [self.infoButton removeFromSuperview];
        self.navBar = nil;
    }
    // **当模态推出时, 添加一个自定义 navigationBar
    // 判断是否为 Phone 设置 navigationBar 高度
    CGFloat navbarHeight = IS_PHONE ? 64.0 : 44.0;
    // 判断模态推出
    if (isPresented) {
        // 创建一个新的 navigationBar
        self.navBar = [[UINavigationBar alloc]initWithFrame:CGRectZero];
        // 约束
        [self.view addSubview:self.navBar];
        PREPCONSTRAINTS(self.navBar, NO);
        ALIGN_VIEW_TOP(self.view, self.navBar);
        ALIGN_VIEW_LEFT(self.view, self.navBar);
        ALIGN_VIEW_RIGHT(self.view, self.navBar);
        CONSTRAIN_HEIGHT(self.navBar, navbarHeight);
    }
    
    // 模态推出时, 右侧 Button 变成 Done
    self.navigationItem.leftBarButtonItem = nil;
    self.navigationItem.rightBarButtonItem = isPresented ? SYSBARBUTTON(UIBarButtonSystemItemDone, @selector(done:)) :nil;
    // 配置 navigation bar
    if (self.navBar) {
        [self.navBar setItems:@[self.navigationItem] animated:NO];
        self.navBar.translucent = YES;
        
    }
    
    // **布局
    // 根据 navBar 是否存在, 设置垂直偏移量
    CGFloat verticalOffSet = (self.navBar != nil) ? navbarHeight : 0.0f;
    CGRect destFrame = CGRectMake(0, verticalOffSet, FRAME_WIDTH(self.view), FRAME_HEIGHT(self.view) - verticalOffSet);
    NSLog(@"%f", verticalOffSet);
    NSLog(@"%f", destFrame.size.height);
    front.view.frame = destFrame;
    back.view.frame = destFrame;
    
    // ***设置 Info Button
    if (self.controllers.count < 2) {
        return;
    }
    // ** 创建 "I" button
    self.infoButton = [UIButton buttonWithType:UIButtonTypeInfoLight];
    self.infoButton.tintColor = [UIColor whiteColor];
    [self.infoButton addTarget:self action:@selector(flip:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.infoButton];
#warning 宽高默认?
    // 约束
    PREPCONSTRAINTS(self.infoButton, NO);
    ALIGN_VIEW_RIGHT_CONSTANT(self.view, self.infoButton, -FRAME_WIDTH(self.infoButton));
    ALIGN_VIEW_BOTTOM_CONSTANT(self.view, self.infoButton, -FRAME_HEIGHT(self.infoButton));
    [front release];
   
}
- (void)done:(id)sender {
    // 返回.
    [self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
}
- (void)flip:(id)sender {
//    if (_controllers.count < 2) {
//        return;
//    }
    // Determine which item is front, which is back
    UIViewController *front =  [_controllers[0] retain];
    UIViewController *back =  [_controllers[1] retain];
    
    // 选择过渡的方向.
    UIViewAnimationOptions transition = _reservedOrder ? UIViewAnimationOptionTransitionFlipFromLeft : UIViewAnimationOptionTransitionFlipFromRight;
    
    // 准备移除front视图控制器, 添加 Back 视图控制器
    [front willMoveToParentViewController:nil];
    [self addChildViewController:back];
# warning ?
    
    // 切换子视图控制器, 从第一个视图控制器过渡到第二个控制器
    [self transitionFromViewController:front toViewController:back duration:0.5f options:transition animations:^{
        /** Button 置顶 */
        [self.view bringSubviewToFront:_infoButton];
        /** navBar 置顶 */
        [self.view bringSubviewToFront:self.navBar];

        [UIView animateWithDuration:0.5f animations:^(){

        }];
    } completion:^(BOOL done){
        
        
        
        // 完成过渡
        [front removeFromParentViewController];
        [back didMoveToParentViewController:self];
        
        self.reservedOrder = !_reservedOrder;
        self.controllers = @[back, front];
        [back release];
        [front release];
    }];

}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    // 如果 子视图控制器 不足2个
//    if (self.controllers.count < 2) {
//        return;
//    }
    ((UIViewController *)_controllers[1]).view.frame = ((UIViewController *)_controllers[0]).view.frame;
    
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
//    if (!_controllers.count)
//    {
//        NSLog(@"Error: No root view controller");
//        return;
//    }
    // 清除子视图控制器
    UIViewController *currentController = (UIViewController *)_controllers[0];
    [currentController willMoveToParentViewController:nil];
    [currentController.view removeFromSuperview];
    [currentController removeFromParentViewController];

}


//- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
//{
//
//    ((UIViewController *)_controllers[1]).view.frame = ((UIViewController *)_controllers[0]).view.frame;
//    NSLog(@"11");
//}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
